<template>
  <div class="tl-dialog">
    <div>
      <span>任务反馈&nbsp;&nbsp;&nbsp;&nbsp;</span>
      <span style="color: #888" v-if="model.submitdate">{{ model.username }}{{ formatDate(model.submitdate) }}填写</span>
    </div>
    <el-form class="tl-form taskForm" ref="form" :model="model" :rules="rules" label-width="150px" :disabled="disableEditSubmit || disableSave" style="margin-right: 10px">
      <el-row>
        <el-col :span="24">
          <el-form-item label="反馈细节" prop="taskfeedbackdetail" :rules="rules.validateRequireSpace">
            <el-input v-model="model.taskfeedbackdetail" type="textarea" :autosize="{ minRows: 1, maxRows: 3 }" maxlength="1000"> </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="任务进度" prop="taskschedule" :rules="rules.validateRequire"> <el-input-number v-model="model.taskschedule" controls-position="right" :step="1" @change="changetaskschedule" :min="0" :max="100" class="unitInputNumber"></el-input-number><span class="unitSpan">%</span> </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="任务风险" prop="taskrisk">
            <el-select v-model="model.taskrisk" :class="taskRiskClassName" clearable>
              <el-option v-for="item in codeModel.taskriskList" :key="item.code" :label="item.name" :value="item.code"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="taskInfo.dmdtask === 1">
          <el-form-item label="是否获取决策链名单" prop="havenamelist" :rules="isFinish ? rules.validateRequire : []">
            <el-select v-model="model.havenamelist" @change="changehavenamelist" clearable>
              <el-option v-for="item in codeModel.enabledList" :key="item.code" :label="item.name" :value="item.code"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="taskInfo.dmdtask === 2">
          <el-form-item label="供应商绩效评价得分" prop="guoscore" :rules="isFinish ? rules.validateRequire : []">
            <el-input v-model="model.guoscore" oninput="this.value=this.value.match(/\d{0,}\.?\d{0,}/)"> </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="taskInfo.dmdtask === 2">
          <el-form-item label="供应商绩效评价排名" prop="guorank" :rules="isFinish ? rules.validateRequire : []">
            <el-input v-model="model.guorank" oninput="this.value=this.value.match(/\d{0,}\.?\d{0,}/)"> </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="taskInfo.dmdtask === 2">
          <el-form-item label="供应商绩效评价档位" prop="guoposition" :rules="isFinish ? rules.validateRequire : []">
            <el-input v-model="model.guoposition"> </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="taskInfo.dmdtask === 3">
          <el-form-item label="是否已获取审查会决策链名单" prop="reviewmeetname" :rules="rules.validateRequire" label-width= "210px">
            <el-select v-model="model.reviewmeetname">
              <el-option v-for="item in codeModel.enabledList" :key="item.code" :label="item.name" :value="item.code"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="23" v-if="taskInfo.dmdtask === 3">
          <el-form-item label="已获取审查会文件内容" prop="documentDetail"  label-width="200px">
            <el-select v-model="documentDetail" placeholder="请选择" filterable multiple clearable @change="changeReviewMeetingDocument">
              <el-option v-for="item in codeModel.reviewmeetingdocumentList" :key="item.code" :label="item.name" :value="item.code"> </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="1" v-if="taskInfo.dmdtask === 3">
            <el-tooltip content="要求必须获取资格要求、技术规范、分标分包、限价、评分细则。" placement="top" style="font-size:20px; margin-top:4px; margin-left: 4px">
              <i class="el-icon-info" style="color: #909399"/>
            </el-tooltip>
        </el-col>
        <el-col :span="8" v-if="taskInfo.dmdtask === 4">
          <el-form-item label="履约评价得分" prop="nankeepscore" :rules="isFinish ? rules.validateRequire : []">
            <el-input v-model="model.nankeepscore" oninput="this.value=this.value.match(/\d{0,}\.?\d{0,}/)"/>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="taskInfo.dmdtask === 4">
          <el-form-item label="履约评价排名" prop="nankeeprank" :rules="isFinish ? rules.validateRequire : []">
            <el-input v-model="model.nankeeprank" oninput="this.value=this.value.match(/\d{0,}\.?\d{0,}/)"/>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="taskInfo.dmdtask === 4">
          <el-form-item label="运行评价得分" prop="nanmovescore" :rules="isFinish ? rules.validateRequire : []">
            <el-input v-model="model.nanmovescore" oninput="this.value=this.value.match(/\d{0,}\.?\d{0,}/)"/>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="taskInfo.dmdtask === 4">
          <el-form-item label="运行评价排名" prop="nanmoverank" :rules="isFinish ? rules.validateRequire : []">
            <el-input v-model="model.nanmoverank" oninput="this.value=this.value.match(/\d{0,}\.?\d{0,}/)"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="任务是否完成" prop="istaskcomplete" :rules="isFinish ? rules.validateRequire : []" v-if="isFinish">
            <el-select v-model="model.istaskcomplete" @change="changeistaskcomplete" :disabled="model.havenamelist === '0' || documentTaskUnfinish">
              <el-option v-for="item in codeModel.istaskcompleteList" :key="item.code" :label="item.name" :value="item.code"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="实际完成日期" prop="taskactualenddate" :rules="isFinish ? rules.validateRequire : []" v-if="isFinish">
            <el-date-picker v-model="model.taskactualenddate" type="date" placeholder="例：2021-01-01" value-format="yyyy-MM-dd" @change="taskactualenddate" :picker-options="aLevelManager ? {} : pickerOptions"></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <tl-approval-history ref="history" sourceType="MpmProjectTaskFeedback" :sourceId="model.id" />
    <div slot="footer" class="dialog-footer" style="float: right;margin-right: 10px">
      <el-button icon="el-icon-delete" type="primary" @click="deleteFeedbackList" :loading="saveLoading" v-if="canDelete">删除</el-button>
      <el-button type="primary" @click="doSubmitEdit" :loading="saveLoading" v-if="!disableEditSubmit" :disabled="disableSave"> <svg-icon icon-class="save" />保存 </el-button>
      <tl-attachment sourceType="MpmProjectTaskFeedback" :sourceId="model.id" :editable="!disableAttachmentButton" :disabled="disableAttachment" v-if="taskInfo.dmdtask !== 3 || canAttachment"></tl-attachment>
      <el-button type="primary" @click="doSubmitApproval" :loading="submitLoading" v-if="!disableEditSubmit" :disabled="disableApproval"> <svg-icon icon-class="send" />提交更新 </el-button>
      <el-button type="primary" @click="$refs.history.visible = true" :disabled="disableApprovalHistory"> <svg-icon icon-class="list" />审批历史 </el-button>
    </div>
  </div>
</template>

<script>
/** mixins */
import { mixin_approval_edit } from '@tapui/mixins/mixin_approval_edit'
import { formatDate } from '@tapui/utils/date'
import { validateNull } from '@tapui/utils/validate'
/** 子组件 */
/** 工具类 */
import { putAction, getAction, postAction, deleteAction } from '@tapui/utils/http'
/** VUE配置 */
export default {
  mixins: [mixin_approval_edit],
  components: {},
  data() {
    return {
      moduleTitle: '任务进度更新',
      urlPrefix: '/mpm/projectTaskFeedback/',
      url: {
        // 额外的url
        queryCanAttachment: '/mpm/projectTaskFeedback/queryCanAttachment',
        queryALevelManager: '/mpm/projectTaskFeedback/queryALevelManager'
      },
      disableAttachmentButton: true,
      pickerOptions: {
        disabledDate: (time) => {
          let now = new Date()
          now.setHours(0, 0, 0, 0)
          return time.getTime() > now.getTime()
        }
      },
      addRules: {
        // 基本信息TAB表单校验
        validateRequireSpace: [{ required: 'true', pattern: '[^ \x22]+', message: '请输入内容', trigger: 'change' }]
      },
      riskClassNames: ['low-level', 'middle-level', 'high-level'],
      canAttachment: false,
      documentDetail: [],
      aLevelManager: false
    }
  },
  props: {
    newValue: {
      type: Object,
      default: () => {}
    },
    canEdit: {
      type: Boolean,
      default: false
    },
    taskInfo: {
      type: Object,
      default: () => {}
    }
  },
  computed: {
    isFinish() {
      return this.model.taskschedule === 100
    },
    canDelete() {
      return validateNull(this.model.id)
    },
    taskRiskClassName() {
      return this.model.taskrisk ? this.riskClassNames[Number.parseInt(this.model.taskrisk)] : ''
    },
    documentTaskUnfinish() {
      return !(this.documentDetail.indexOf('1') > -1 && this.documentDetail.indexOf('2') > -1 && this.documentDetail.indexOf('3') > -1 && this.documentDetail.indexOf('4') > -1 && this.documentDetail.indexOf('5') > -1) && this.taskInfo.dmdtask === 3
    }
  },
  watch: {
    newValue: {
      handler(value, oldvalue) {
        this.model = value
        // 新增、编辑、查看权限确定
        if (!this.model.hasOwnProperty('id')) {
          this.isAdd = true
          this.disableEditSubmit = false
        } else if (this.model.state === 1 || this.model.state === 9 || !this.canEdit) {
          this.isAdd = false
          this.disableEditSubmit = true
        } else {
          this.isAdd = false
          this.disableEditSubmit = false
        }
        if (validateNull(oldvalue) || oldvalue.id !== value.id) {
          this.loaded()
        }
        this.addAttachment()
      },
      immediate: true,
      deep: true,
      riskClassNames: ['low-level', 'middle-level', 'high-level']
    }
  },
  methods: {
    // 格式化日期 yyyy-MM-dd
    dateFormat(row, column, cellValue, index) {
      let dateValue = row[column.property]
      if (dateValue && dateValue.length > 0) {
        return formatDate(new Date(dateValue.replace(new RegExp(/-/gm), '/')), 'yyyy-MM-dd')
      } else {
        return ''
      }
    },
    formatDate(date) {
      return validateNull(date) ? '' : '于' + formatDate(new Date(date ? date.toString().replace(/\-/g, '/') : date), 'yyyy-MM-dd HH:mm')
    },
    taskactualenddate(e) {
      var taskactualstartdate = new Date(this.model.taskactualstartdate).getTime()
      var taskactualenddate = new Date(this.model.taskactualenddate).getTime()
      var nowdate = new Date().getTime()
      if (!this.aLevelManager) {
        if (taskactualenddate > nowdate) {
          this.$tap.alert('任务实际完成日期不能晚于当前日期！', 'warning')
          this.model.taskactualenddate = null
          return
        }
        if (taskactualenddate < taskactualstartdate) {
          this.$tap.alert('任务实际完成日期不能早于任务实际开始日期！', 'warning')
          this.model.taskactualenddate = null
          return
        }
      }
      // 计划结束日期存储为选择日期的的23：59：59
      let date = new Date(taskactualenddate)
      let timeDate = ''
      let Y = date.getFullYear() + '-'
      let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
      let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' '
      let h = 23 + ':'
      let m = 59 + ':'
      let s = 59
      timeDate = Y + M + D + h + m + s
      this.$set(this.model, 'taskactualenddate', timeDate)
    },
    changetaskschedule() {
      if (this.model.taskschedule === 100) {
        if (this.model.havenamelist === '0') {
          this.$set(this.model, 'istaskcomplete', '0')
          this.$set(this.model, 'taskstate', '3')
        }
        if (this.documentTaskUnfinish) {
          this.$set(this.model, 'istaskcomplete', '0')
          this.$set(this.model, 'taskstate', '3')
        }
      } else {
        this.$set(this.model, 'taskstate', '1')
        this.$set(this.model, 'istaskcomplete', null)
        this.$set(this.model, 'taskactualenddate', null)
      }
    },
    // 是否获取决策链名单的值发生变化
    changehavenamelist(data) {
      if (data === '0' && this.isFinish) {
        // 如果任务未完成
        this.$set(this.model, 'istaskcomplete', '0')
        this.$set(this.model, 'taskstate', '3')
      }
    },
    // 审查会文件内容的值发生变化
    changeReviewMeetingDocument(data) {
        if (this.documentTaskUnfinish && this.isFinish) {
          this.$set(this.model, 'istaskcomplete', '0')
          this.$set(this.model, 'taskstate', '3')
        }
    },
    // 是否完成任务的值发生变化
    changeistaskcomplete(data) {
      if (data === '1') {
        // 如果任务完成，则任务状态为已完成
        this.$set(this.model, 'taskstate', '2')
      } else if (data === '0') {
        // 如果任务未完成，则任务状态为未完成关闭
        this.$set(this.model, 'taskstate', '3')
      }
    },
    assignDefaultValue() {
      if (this.isAdd) {
        if (this.codeModel.flowidList && this.codeModel.flowidList.length > 0) {
          this.$set(this.model, 'flowid', parseInt(this.codeModel.flowidList[0].id))
        }
        this.$set(this.model, 'applyorgcode', this.org.code)
        this.$set(this.model, 'applyorgname', this.org.name)
        this.$set(this.model, 'applydeptcode', this.dept.code)
        this.$set(this.model, 'applydeptname', this.dept.fullname)
        this.$set(this.model, 'applyusercode', this.user.code)
        this.$set(this.model, 'applyusername', this.user.name)
        this.$set(this.model, 'usercode', this.user.code)
        this.$set(this.model, 'username', this.user.name)
        this.$set(this.model, 'deptcode', this.dept.code)
        this.$set(this.model, 'orgcode', this.org.code)
        this.$set(this.model, 'feedbackdate', new Date())
        this.$set(this.model, 'taskid', this.taskInfo.id)
        this.$set(this.model, 'taskname', this.taskInfo.taskname)
        this.$set(this.model, 'taskschedule', this.taskInfo.taskschedule)
        this.$set(this.model, 'taskstate', this.taskInfo.taskstate)
        this.$set(this.model, 'planstartdate', this.taskInfo.planstartdate.substring(0, 10))
        this.$set(this.model, 'planenddate', this.taskInfo.planenddate.substring(0, 10))
        this.$set(this.model, 'taskdistributedate', this.taskInfo.taskdistributedate.substring(0, 10))
        this.$set(this.model, 'projectcode', this.taskInfo.projectcode)
        this.$set(this.model, 'taskactualstartdate', this.taskInfo.actualstartdate)
        this.$set(this.model, 'taskdetail', this.taskInfo.taskdetail)
        this.$set(this.model, 'customerattach', this.taskInfo.customerattach)
        this.$set(this.model, 'improveplan', this.taskInfo.improveplan)
        this.$set(this.model, 'istaskfeedback', '1')
      }
    },
    loaded() {
      validateNull(this.model.reviewmeetingdocument) ? this.$set(this, 'documentDetail', []) : this.$set(this, 'documentDetail', this.model.reviewmeetingdocument.split(','))
      // 获取项目是否为A级项目经理为省总的项目
      this.getProjectALevelManager()
    },
    afterDelApproval() {
      this.disableAttachmentButton = false
    },
    /** 保存确认 */
    // doSubmitEdit() {
    //   if (!this.beforeSubmit()) {
    //     return
    //   }
    //   this.$refs.form.validate(valid => {
    //     if (valid) {
    //       if (this.isAdd) {
    //         this.doAdd()
    //         return true
    //       } else {
    //         this.doEdit()
    //       }
    //     } else {
    //       return false
    //     }
    //   })
    // },
    /** 执行新增提交 */
    doAdd() {
      this.saveLoading = true
      // 增加唯一单号
      postAction(this.url.add + '?billuid=' + this.uid, this.model)
        .then((res) => {
          if (res.success) {
            this.$tap.message('添加成功', 'success')
            this.model = res.result
            this.disableAttachmentButton = false
            this.isAdd = false
            this.$emit('refresh')
          } else {
            this.$tap.alert(res.message, 'warning')
          }
          this.afterSubmit()
          this.saveLoading = false
        })
        .catch((err) => {
          this.saveLoading = false
        })
    },
    /** 提交审批 */
    doSubmitApproval() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.model.taskschedule === 100 && !this.model.taskactualenddate) {
            this.$tap.alert('请填写实际完成日期！')
            return
          }
          if (this.model.taskschedule !== 100 && this.model.taskactualenddate) {
            this.$tap.alert('任务进度未到100%，请删除实际完成日期！')
            return
          }
          if (this.model.taskschedule !== 100) {
            this.$set(this.model, 'taskactualenddate', '')
          }
          if (!this.url.submit) {
            this.$tap.alert('请设置审批地址!', 'warning')
            return
          }
          if (!this.beforeSubmit()) {
            return
          }
          if (!this.beforeApproval()) {
            return
          }
          this.submitLoading = true
          this.$tap
            .confirm('确定提交更新吗？提交后，更新内容不可修改！')
            .then((_) => {
              putAction(this.url.submit, this.model).then((res) => {
                if (res.success) {
                  this.$tap.message(res.message, 'success')
                  this.queryData(this.model.id)
                  this.afterApproval()
                  this.$emit('refresh')
                  this.visible = false
                } else {
                  this.$tap.alert(res.message, 'warning')
                }
                this.submitLoading = false
              })
            })
            .catch((_) => {
              this.submitLoading = false
            })
        }
      })
    },
    /** 页面打开时执行 - zhanglongfei 2019.10.18 */
    open() {
      this.model = {}
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
        if (this.isAdd === true) {
          this.title = '新增' + this.moduleTitle
          // 需要添加重复判断
          if (this.$store.getters.param.isAvoidRepeat === true) {
            this.queryBillUid()
          }
          if (this.isQueryInitData === true) {
            // 后台进行数据初始化
            this.queryInitData().then((_) => {
              this.assignDefaultValue()
              this.loaded()
            })
          } else {
            // 前台进行数据初始化
            this.$set(this.model, 'enabled', 1)
            this.$set(this.model, 'sortcode', 0)
            this.assignDefaultValue()
            this.loaded()
          }
        } else if (this.disableEditSubmit === false) {
          this.title = '编辑' + this.moduleTitle
          this.queryData(this.id).then((_) => {
            this.loaded()
          })
        } else {
          this.title = '查看' + this.moduleTitle
          this.queryData(this.id).then((_) => {
            this.loaded()
          })
        }
      })
    },
    // 当点击删除按钮时，传递事件，删除feedbackList中新增内容
    deleteFeedbackList() {
      this.$emit('deleteList')
    },
    // 获取附件是否能够查看的权限
    queryCanAttachment() {
      getAction(this.url.queryCanAttachment, { qry_projectcode: this.model.projectcode }).then(res => {
        if (res.success) {
          this.canAttachment = res.result
        }
      })
    },
    beforeSubmit() {
      if (Array.isArray(this.documentDetail)) {
        this.$set(this.model, 'reviewmeetingdocument', this.documentDetail.join(','))
      }
      return true
    },
    addAttachment() {
      this.disableAttachmentButton = true
      // 如果已提交审批但未审批完成且附件数量不为0，可以上传附件，保存未提交审批，可以上传附件
      if (this.isAdd === false && this.disableEditSubmit === true && this.model.state !== 9) {
        var params = {
          sourceType: 'MpmProjectTaskFeedback',
          sourceId: this.model.id
        }
        this.disableAttachmentButton = false
        getAction('/cbo/attachment/calculateCount', params).then((res) => {
          if (res.success) {
            if (res.result === 0) {
              this.disableAttachmentButton = true
            }
          }
        })
      } else if (this.isAdd === false && this.disableEditSubmit === false) {
        this.disableAttachmentButton = false
      }
      // 页面加载完毕执行
      if (!this.isAdd && this.model.docno) {
        this.title = this.title + `（单据编号：${this.model.docno}）`
      }
    },
    getProjectALevelManager() {
      getAction(this.url.queryALevelManager, { projectcode: this.model.projectcode }).then(res => {
        if (res.success) {
         this.aLevelManager = res.result.aLevelManager
        }
      })
    }
  },
  created() {
    // 获取附件是否能够查看的权限
    if (this.taskInfo.dmdtask === 3) {
      this.queryCanAttachment()
    }
  }
}
</script>

<style lang="scss" scoped>
.taskForm {
  margin-top: 15px;
  margin-left: -50px;
  .el-row {
    margin-bottom: 2px;
  }
}

$riskLevels: high-level, middle-level, low-level;
$riskColors: #ff6363, #ffe119, #bfef45;
//for 循环 根据风险中高 匹配颜色和字体样式
@for $i from 1 through 3 {
  .#{nth($riskLevels,$i)} /deep/ .el-input__inner {
    background-color: nth($riskColors, $i) !important;
    color: rgba(27, 27, 27, 0.5) !important;
    font-weight: 600;
  }
}
</style>
